import { h } from "vue";
import { message, Modal } from "ant-design-vue";
import { useBaseApiFactory, EventEmitTool } from "@webxue/https";
import { useApiConfig } from "../configs/api.config";
import { useUserStore } from "../stores/user.store";
import { useWebxRouteTabs } from "@webxue/vue3-antdv-ui";
import { useConfigStore } from "@/stores/config.store";
import router from "../router";

export const BaseApi = useBaseApiFactory({
  baseURL: useApiConfig().adminBaseUrl,
  // 获取加密盐
  async getSalt(){
    return useConfigStore().publicConfigJson?.authSalt;
  },
  getConfig(config) {
    // 鉴权token
    if (useUserStore().userTK?.token) {
      config.headers["Authorization"] = "Bearer " + useUserStore().userTK?.token;
    }

    return config;
  },
  onSuccess(response) {
    // 业务判断提示消息
    if (response.success) {
      // message.success(response.message || "操作成功").then();
    } else {
      const content = response.message || "操作失败";
      if (response.msgType === "modal") {
        Modal.error({
          title: "温馨提示",
          content: h("div", {
            innerHTML: content
          })
        });
      } else if (response.msgType === "toast") {
        message.error(content).then();
      }
    }
  }
}).api;

// 鉴权失败，退出登录
EventEmitTool.on("API:UN_AUTH", () => {
  useUserStore().logout();
});

// 数据被删除，404
EventEmitTool.on("API:FIND:NOT_FUND", () => {
  const { closeActiveTab, addTab } = useWebxRouteTabs({ router });
  // 关闭当前激活的页签
  closeActiveTab();
  // 跳转到404页签
  addTab({
    key:"page-404",
    title:"404",
    href:"/404",
  })
});
